package com.heima.kafka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * Kafka主题生产者
 */
@RestController
public class ProducerController {

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @GetMapping("/sendKeyValue/{key}/{value}")
    public String sendKeyValue(@PathVariable("key") String key, @PathVariable("value") String value){
        kafkaTemplate.send("testTopic",  key,value );

        return "OK";
    }

    @GetMapping("/sendValue/{value}")
    public String sendValue( @PathVariable("value") String value) throws ExecutionException, InterruptedException {
        //发送类型：发送并忘记
        //kafkaTemplate.send("testTopic",value );

        //发送类型：同步发送
        //SendResult sendResult = (SendResult)kafkaTemplate.send("testTopic", value).get();
        //System.out.println(sendResult.getRecordMetadata().offset());

        //发送类型：异步发送
        kafkaTemplate.send("testInTopic", value).addCallback(new ListenableFutureCallback() {
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onSuccess(Object o) {
                SendResult sendResult = (SendResult)o;
                System.out.println(sendResult.getRecordMetadata().offset());
            }
        });

        return "OK";
    }
}
